package com.djakapm.markdown.editor.action;

import com.djakapm.markdown.editor.AppConstant;
import com.djakapm.markdown.editor.Application;
import com.djakapm.swing.component.tab.Tab;

import javax.swing.*;
import java.awt.event.ActionEvent;

public class CloseFileAction extends AbstractAction {
    private Application application;


    public CloseFileAction(Application application){
        this.application = application;
        this.putValue(Action.SHORT_DESCRIPTION, AppConstant.CLOSE_FILE_TOOLTIP_LABEL);
    }

    private void removeTab(Tab tab,int selectedIndex){
        tab.removeTabAt(selectedIndex);
        this.application.removeContent(selectedIndex);
    }

    private void saveContent(int selectedIndex){
        this.application.saveContentAt(selectedIndex);
    }


    private boolean isNewFile(Tab tab,int selectedIndex){
        return AppConstant.NEW_FILE_TITLE.equals(tab.getTitleAt(selectedIndex));
    }

    public void actionPerformed(ActionEvent e) {
        Tab tab;
        String message;
        int selectedIndex;
        int result;
        if(e.getSource() == null){ return; }
        tab = (Tab) e.getSource();
        selectedIndex = tab.getOverTabIndex();

        if(!this.application.isContentModifiedAt(selectedIndex)){
            this.removeTab(tab,selectedIndex);
            return;
        }

        message = (isNewFile(tab,selectedIndex) ? AppConstant.NEW_FILE_MODIFIED_LABEL : AppConstant.FILE_MODIFIED_LABEL);
        result = JOptionPane.showConfirmDialog(null,message,AppConstant.SAVE_CHANGES_LABEL,JOptionPane.YES_NO_CANCEL_OPTION);

        switch(result){
            case JOptionPane.NO_OPTION:
                this.removeTab(tab,selectedIndex);
                break;
            case JOptionPane.YES_OPTION:
                this.saveContent(selectedIndex);
                this.removeTab(tab,selectedIndex);
                break;
            case JOptionPane.CANCEL_OPTION:
                break;
        }
    }
}
